/**
 * $version:  0.1 
 * $Date: 2011-01-21 
 *
 * Copyright (C) 2010-2011 Jawa Software. All rights reserved.
 *
 */

package org.jawa.user;

import java.util.AbstractCollection;
import java.util.Iterator;
import java.util.NoSuchElementException;


/**
 * 
 * 根据一个 userId 的数组来模拟一下用户集合.如果在遍历集合的时候，任何一个 userId 找不到对应的用户信息，那么就会跳过.
 * 
 */
public class UserCollection<User> extends AbstractCollection {

	private Long[] elements;

	/**
	 * 用户集合构造.
	 */
	public UserCollection(Long[] elements) {
		this.elements = elements;
	}

	@Override
	public Iterator<User> iterator() {
		return new UserIterator();
	}

	@Override
	public int size() {
		return elements.length;
	}

	private class UserIterator implements Iterator {

		private int currentIndex = -1;
		private Object nextElement = null;

		public boolean hasNext() {
			// 如果已经到了集合的尾部，则不需要进行加载数据的判断了.
			if (currentIndex + 1 >= elements.length && nextElement == null) {
				return false;
			}
			// 否则, 如果下一个对象为空，先进行加载.
			if (nextElement == null) {
				nextElement = getNextElement();
				if (nextElement == null) {
					return false;
				}
			}
			return true;
		}

		public Object next() throws java.util.NoSuchElementException {
			Object element;
			if (nextElement != null) {
				element = nextElement;
				nextElement = null;
			} else {
				element = getNextElement();
				if (element == null) {
					throw new NoSuchElementException();
				}
			}
			return element;
		}

		public void remove() throws UnsupportedOperationException {
			throw new UnsupportedOperationException();
		}

		/**
		 * 返回下一个存在的 对象，如果为空，代表没有更多的下一个对象了。
		 * 
		 * @return 下一个存在的 对象.
		 */
		private Object getNextElement() {
			while (currentIndex + 1 < elements.length) {
				currentIndex++;
				Object element = null;
				try {
					element = UserManager.getInstance().getUser(
							elements[currentIndex]);
				} catch (UserNotFoundException unfe) {
					// 忽略.
				}
				if (element != null) {
					return element;
				}
			}
			return null;
		}
	}
}